<?php

namespace app\api\controller;

use AlibabaCloud\SDK\Alimt\V20181012\Models\TranslateGeneralRequest;
use app\common\controller\Api;
use TencentCloud\Tmt\V20180321\TmtClient;
use TencentCloud\Common\Credential;
use TencentCloud\Tmt\V20180321\Models\TextTranslateRequest;
use think\Config;
use think\Db;
use think\Env;
use think\View;

use AlibabaCloud\SDK\Alimt\V20181012\Alimt;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config as aliConfig;
use AlibabaCloud\SDK\Alimt\V20181012\Models\CreateDocTranslateTaskRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class Test extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    private $bannerJson = '[
  {
    "type":"img",
    "img": "https://material-product.oss-cn-hongkong.aliyuncs.com/banner/main_banner_1.png",
    "link": "https://material-product.oss-cn-hongkong.aliyuncs.com/banner/main_banner_big_1.png"
  },
  {
    "type":"img",
    "img": "https://material-product.oss-cn-hongkong.aliyuncs.com/banner/main_banner_2.png",
    "link": "https://material-product.oss-cn-hongkong.aliyuncs.com/banner/main_banner_big_2.png"
  },
  {
    "type":"img",
    "img": "https://material-product.oss-cn-hongkong.aliyuncs.com/banner/main_banner_3.png",
    "link": "https://material-product.oss-cn-hongkong.aliyuncs.com/banner/main_banner_big_3.png"
  },
  {
    "type":"img",
    "img": "https://material-product.oss-cn-hongkong.aliyuncs.com/banner/main_banner_4.png",
    "link": "https://material-product.oss-cn-hongkong.aliyuncs.com/banner/main_banner_big_4.png"
  }
]';

    public function _initialize()
    {
        parent::_initialize();

    }

    public function tt(){
        echo json_decode("SWRM15  \u51b7\u9593\u5727\u9020\u30e9\u30a4\u30f3");
        echo 'SWRM15  \u51b7\u9593\u5727\u9020\u30e9\u30a4\u30f3';
    }
    public function aliTrans()
    {
        echo translate_company('上海の睿雄のグループは中国.全経営陣で冷間ヘッディングの質の鋼線に焦点を合わせる企業の20年間の経験がありますベンチマーク企業です。私たちは、自動車産業の多くのティア1サプライヤーと良好な関係を築いており、すべての線材はブランドの製鉄所から供給されています。すべての注文は100%追跡可能です。','ja','en');die;
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html。
        $config = new aliConfig([
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
            "accessKeyId" => Env::get("app.aliak"),
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
            "accessKeySecret" => Env::get("app.alisk")
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/alimt
        $config->endpoint = "mt.cn-hangzhou.aliyuncs.com";
        $client = new Alimt($config);

        $translateGeneralRequest = new TranslateGeneralRequest([
            "formatType" => "text",
            "sourceLanguage" => "zh",
            "targetLanguage" => "en",
            "sourceText" => "你好",
            "scene" => "general"
        ]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $resp = $client->translateGeneral($translateGeneralRequest);
            if($resp->body->code)
            print_r($resp->body->data->toMap());
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            var_dump($error->message);
            var_dump("---------");
            // 诊断地址
            var_dump($error->data["Recommend"]);
            Utils::assertAsString($error->message);
        }

    }

    //中文的三级分类改为英文的
    public function reProduct4(){
        $productModel = new \app\common\model\Product();
        $products = $productModel->select();
        foreach ($products as $product){
            $product['content'] = json_decode($product['content'],1);
//            print_r(json_encode($product['content']));die;
            $product['content_zh'] = json_decode($product['content_zh'],1);
//            print_r($product['content_zh']['category'][2]);die;
            $tmp = $product['content_zh'];
            $tmp['category'][2] = $product['content']['category'][2];
            $product['content_zh'] = $tmp;
            $product['content_zh'] = json_encode($product['content_zh'],JSON_UNESCAPED_UNICODE);
            $product['content'] = json_encode($product['content']);
//            print_r($product);die;
            $product->save();
            echo $product['id'].'-done'."\r\n";
        }
    }

    /**
     *  type 字段改成 video
     *  然后 link 改成
     * 0
     * https://player.youku.com/embed/XNjQwNDUzNjAwNA==
     * 1
     * https://player.youku.com/embed/XNjQwNDUzOTU0OA==
     * 2
     * https://player.youku.com/embed/XNjQwNDUzODI1Mg==
     * 3
     * https://player.youku.com/embed/XNjQxMTIwNjIzNg==
     * 4
     * https://player.youku.com/embed/XNjQxMTIxMjExNg==
     * 5
     * https://player.youku.com/embed/XNjQxMTIxMjExNg==
     */
    public function reProduct3(){
        $linkArr = [
            'https://player.youku.com/embed/XNjQwNDUzNjAwNA==',
            'https://player.youku.com/embed/XNjQwNDUzOTU0OA==',
            'https://player.youku.com/embed/XNjQwNDUzODI1Mg==',
            'https://player.youku.com/embed/XNjQxMTIwNjIzNg==',
            'https://player.youku.com/embed/XNjQxMTIxMjExNg==',
            'https://player.youku.com/embed/XNjQxMTIxMjExNg==',
        ];
        $productModel = new \app\common\model\Product();
        $products = $productModel->select();
        foreach ($products as $product){
            $product['content'] = json_decode($product['content'],1);
//            print_r($product['content']['technical']['process']);die;
//            $product['content']['banner'] = $bannerArr;   //这种写法会报错，换成下面的临时变量写法
            $tmp = $product['content'];
            for($i=0;$i<6;$i++){
                if(isset($tmp['technical']['process'][$i])){
                    $tmp['technical']['process'][$i]['type'] = 'video';
                    $tmp['technical']['process'][$i]['link'] = $linkArr [$i];
                }
            }
            $product['content'] = $tmp;
            $product['content'] = json_encode($product['content']);
//            print_r(json_encode($product['content']));die;
            $product['content_zh'] = json_decode($product['content_zh'],1);
            $tmp2 = $product['content_zh'];
            for($i=0;$i<6;$i++){
                if(isset($tmp2['technical']['process'][$i])){
                    $tmp2['technical']['process'][$i]['type'] = 'video';
                    $tmp2['technical']['process'][$i]['link'] = $linkArr [$i];
                }
            }
            $product['content_zh'] = $tmp2;
            $product['content_zh'] = json_encode($product['content_zh'],JSON_UNESCAPED_UNICODE);
//            print_r($product);die;
            $product->save();
            echo $product['id'].'-done'."\r\n";
        }
    }

    /**
     *  paragraoh - > 对应的banner 大图小图都用一个就行
     * 1.技术交货条件
     * https://material-product.oss-cn-hongkong.aliyuncs.com/banner/240731/d9fa9c1b-1722415106714.png
     * 2.表面质量
     * https://material-product.oss-cn-hongkong.aliyuncs.com/banner/240731/87f463c9-1722415170108.jpg
     * 3.应用行业
     * https://material-product.oss-cn-hongkong.aliyuncs.com/banner/240731/af18b9dc-1722415207950.jpg
     */
    public function reProduct2(){
        $productModel = new \app\common\model\Product();
        $products = $productModel->select();
        foreach ($products as $product){
            $product['content'] = json_decode($product['content'],1);
//            print_r($product['content']);die;
//            $product['content']['banner'] = $bannerArr;   //这种写法会报错，换成下面的临时变量写法
            $tmp = $product['content'];
            if(isset($tmp['detail']['paragraph'][0]['banner']['img'])){
                $tmp['detail']['paragraph'][0]['banner']['img'] = 'https://material-product.oss-cn-hongkong.aliyuncs.com/banner/240731/d9fa9c1b-1722415106714.png';
                $tmp['detail']['paragraph'][0]['banner']['link'] = 'https://material-product.oss-cn-hongkong.aliyuncs.com/banner/240731/d9fa9c1b-1722415106714.png';
            }
            if(isset($tmp['detail']['paragraph'][1]['banner']['img'])){
                $tmp['detail']['paragraph'][1]['banner']['img'] = 'https://material-product.oss-cn-hongkong.aliyuncs.com/banner/240731/87f463c9-1722415170108.jpg';
                $tmp['detail']['paragraph'][1]['banner']['link'] = 'https://material-product.oss-cn-hongkong.aliyuncs.com/banner/240731/87f463c9-1722415170108.jpg';
            }
            if(isset($tmp['detail']['paragraph'][2]['banner']['img'])){
                $tmp['detail']['paragraph'][2]['banner']['img'] = 'https://material-product.oss-cn-hongkong.aliyuncs.com/banner/240731/af18b9dc-1722415207950.jpg';
                $tmp['detail']['paragraph'][2]['banner']['link'] = 'https://material-product.oss-cn-hongkong.aliyuncs.com/banner/240731/af18b9dc-1722415207950.jpg';
            }
            $product['content'] = $tmp;
            $product['content'] = json_encode($product['content']);
//            print_r(json_encode($product['content']));die;
            $product['content_zh'] = json_decode($product['content_zh'],1);
            $tmp2 = $product['content_zh'];
            if(isset($tmp2['detail']['paragraph'][0]['banner']['img'])){
                $tmp2['detail']['paragraph'][0]['banner']['img'] = 'https://material-product.oss-cn-hongkong.aliyuncs.com/banner/240731/d9fa9c1b-1722415106714.png';
                $tmp2['detail']['paragraph'][0]['banner']['link'] = 'https://material-product.oss-cn-hongkong.aliyuncs.com/banner/240731/d9fa9c1b-1722415106714.png';
            }
            if(isset($tmp2['detail']['paragraph'][1]['banner']['img'])){
                $tmp2['detail']['paragraph'][1]['banner']['img'] = 'https://material-product.oss-cn-hongkong.aliyuncs.com/banner/240731/87f463c9-1722415170108.jpg';
                $tmp2['detail']['paragraph'][1]['banner']['link'] = 'https://material-product.oss-cn-hongkong.aliyuncs.com/banner/240731/87f463c9-1722415170108.jpg';
            }
            if(isset($tmp2['detail']['paragraph'][2]['banner']['img'])){
                $tmp2['detail']['paragraph'][2]['banner']['img'] = 'https://material-product.oss-cn-hongkong.aliyuncs.com/banner/240731/af18b9dc-1722415207950.jpg';
                $tmp2['detail']['paragraph'][2]['banner']['link'] = 'https://material-product.oss-cn-hongkong.aliyuncs.com/banner/240731/af18b9dc-1722415207950.jpg';
            }
            $product['content_zh'] = $tmp2;
            $product['content_zh'] = json_encode($product['content_zh'],JSON_UNESCAPED_UNICODE);
//            print_r($product);die;
            $product->save();
            echo $product['id'].'-done'."\r\n";
        }
    }

    /**
     * 修改产品内容
     * banner统一替换为：
     * [
     * {
     * "img": "https://material-product.oss-cn-hongkong.aliyuncs.com/banner/main_banner_1.png",
     * "link": "https://material-product.oss-cn-hongkong.aliyuncs.com/banner/main_banner_big_1.png"
     * },
     * {
     * "img": "https://material-product.oss-cn-hongkong.aliyuncs.com/banner/main_banner_2.png",
     * "link": "https://material-product.oss-cn-hongkong.aliyuncs.com/banner/main_banner_big_2.png"
     * },
     * {
     * "img": "https://material-product.oss-cn-hongkong.aliyuncs.com/banner/main_banner_3.png",
     * "link": "https://material-product.oss-cn-hongkong.aliyuncs.com/banner/main_banner_big_3.png"
     * },
     * {
     * "img": "https://material-product.oss-cn-hongkong.aliyuncs.com/banner/main_banner_4.png",
     * "link": "https://material-product.oss-cn-hongkong.aliyuncs.com/banner/main_banner_big_4.png"
     * }
     * ]
     * 然后：
     * https://www.xingda-group.com/images/banner/X12Cr13.jpg  换成图1链接
     * @return void
     */
    public function reProduct(){
        $bannerArr = json_decode($this->bannerJson,1);
//        print_r($bannerArr);die;
        $productModel = new \app\common\model\Product();
        $products = $productModel->select();
        foreach ($products as $product){
//            $product['content_zh'] = json_decode($product['content_zh'],1);
            $product['content'] = str_replace('https://www.xingda-group.com/images/banner/X12Cr13.jpg','https://material-product.oss-cn-hongkong.aliyuncs.com/banner/main_banner_1.png',$product['content']);
            $product['content'] = json_decode($product['content'],1);
//            print_r($product['content']);die;
//            $product['content']['banner'] = $bannerArr;   //这种写法会报错，换成下面的临时变量写法
            $tmp = $product['content'];
            $tmp['banner'] = $bannerArr;
            $product['content'] = $tmp;
            $product['content'] = json_encode($product['content']);
//            print_r(json_encode($product['content']));die;
            $product['content_zh'] = str_replace('https://www.xingda-group.com/images/banner/X12Cr13.jpg','https://material-product.oss-cn-hongkong.aliyuncs.com/banner/main_banner_1.png',$product['content_zh']);
            $product['content_zh'] = json_decode($product['content_zh'],1);
            $tmp2 = $product['content_zh'];
            $tmp2['banner'] = $bannerArr;
            $product['content_zh'] = $tmp2;
            $product['content_zh'] = json_encode($product['content_zh'],JSON_UNESCAPED_UNICODE);
            $product->save();
            echo $product['id'].'-done'."\r\n";
        }
    }


    public function buildHtml($htmlfile = '', $data = ['errInfo'=>[]])
    {
        // 实例化视图类，并指定模板文件和输出文件
        $view = new View();
        $html = $view->fetch('test/install', $data);
        // 输出到文件
        // 确保目录存在
        $filePath = './static/html/index.html';
        $dirName = pathinfo($filePath, PATHINFO_DIRNAME);
        if (!is_dir($dirName)) {
            mkdir($dirName, 0755, true); // 第三个参数 true 表示可以创建多级目录
        }
        file_put_contents($filePath, $html);
    }

    public function trans(){
        set_time_limit(0);
        ini_set('max_execution_time', '0');

        $lanArr = [
            'zh'=>['lan'=>'zh','field'=>'content_zh'],
//            'en'=>['lan'=>'en','field'=>'content_en'],
//            'ou'=>['lan'=>'de','field'=>'content_ou'],//德语
//            'rb'=>['lan'=>'ja','field'=>'content_rb'],
//            'hy'=>['lan'=>'ko','field'=>'content_hy'],//韩国
////            'agt'=>['lan'=>'zh','field'=>'content_agt'],//阿根廷
//            'els'=>['lan'=>'ru','field'=>'content_els'],
            ];

        //欧洲标准
//        $products = Db::table("fa_zz_product")->where(['language'=>'欧洲标准89'])->select();
////        print_r($products);die;
//        foreach ($lanArr as $lan){
//            $useChinese = in_array($lan['lan'],['ja','ko']);
////            $useChinese = false;
//            $lan_source =  $useChinese?'zh':'de';
//            $content_field = $useChinese?'content_zh':'content';
//            $this->trasProduct($products,new \app\common\model\Product,$lan['field'],$lan_source,$lan['lan'],$content_field);
//        }

//        //日本
//        $products = Db::table("fa_zz_product")->where(['language'=>'日本'])->select();
////        print_r($products);die;
//        foreach ($lanArr as $lan){
//            $lan_source =  in_array($lan['lan'],['ru','de'])?'zh':'ja';
//            $content_field = in_array($lan['lan'],['ru','de'])?'content_zh':'content';
//            $this->trasProduct($products,new \app\common\model\Product,$lan['field'],$lan_source,$lan['lan'],$content_field);
//        }
//
////        //iso（英语）
//        $products = Db::table("fa_zz_product")->where(['language'=>'iso105'])->select();
////        print_r($products);die;
//        foreach ($lanArr as $lan){
//            $this->trasProduct($products,new \app\common\model\Product,$lan['field'],'en',$lan['lan']);
//        }

        //美国标准（英语）
        $products = Db::table("fa_zz_product")->where(['language'=>'美国标准'])->select();
//        print_r($products);die;
        foreach ($lanArr as $lan){
            $this->trasProduct($products,new \app\common\model\Product,$lan['field'],'en',$lan['lan']);
        }

        //异形管（中文）
//        $products = Db::table("fa_zz_product")->where(['language'=>'异形管'])->select();
////        print_r($products);die;
//        foreach ($lanArr as $lan){
//            $this->trasProduct($products,new \app\common\model\Product,$lan['field'],'zh',$lan['lan']);
//        }
//        //国标（中文）
//        $products = Db::table("fa_zz_product")->where(['language'=>'国标'])->select();
////        print_r($products);die;
//        foreach ($lanArr as $lan){
//            $this->trasProduct($products,new \app\common\model\Product,$lan['field'],'zh',$lan['lan']);
//        }
        echo 'done';
    }

    /**
     * @param $products
     * @param $model
     * @param $field    需要填充的字段
     * @param $lan_source
     * @param $lan_target
     * @param $content_field 内容字段，如翻译语言不支持，则用该字段指定内容进行翻译，比如：日语翻译俄罗斯语不支持，就改为content_zh来翻译
     * @return void
     */
    private function trasProduct($products,$model,$field,$lan_source = 'zh',$lan_target = 'en',$content_field='content'){
        foreach ($products as $product){
//            print_r($product);die;
            if(!empty($product[$field])){
                continue;
            }

            $content = json_decode(preg_replace('/[\x00-\x1F]/','', $product[$content_field]),1);
            //本语言不需要翻译
            if($lan_target == $lan_source){
                $product[$field] = json_encode($content, JSON_UNESCAPED_UNICODE);
                $model->update($product);
                continue;
            }
//            print_r($content);die;
//            continue;
            if (json_last_error() != JSON_ERROR_NONE) {
                // 处理错误，可以根据错误类型提供相应的处理方式
                echo "JSON 解析出错: " . json_last_error_msg();
                var_dump($product['id']);
                die;
            }
            $en_content = $content;
            $en_content['product_name'] =translate($content['product_name'], $lan_source, $lan_target);
            foreach ($en_content['category'] as $k => $v) {
                $en_content['category'][$k] =translate($v, $lan_source, $lan_target);
            }
            foreach ($en_content['banner'] as $k => &$v) {
                $v['des'] =translate($v['des'], $lan_source, $lan_target);
                $v['title'] =translate($v['title'], $lan_source, $lan_target);
            }
            foreach ($en_content['attributes'] as $k => &$v) {
                $v['name'] =translate($v['name'], $lan_source, $lan_target);
                $v['value'] =translate($v['value'], $lan_source, $lan_target);
            }
            $en_content['detail']['des'] =translate($en_content['detail']['des'], $lan_source, $lan_target);

            foreach ($en_content['detail']['paragraph'] as &$vv) {
                if (!empty($vv['title'])) {
                    $vv['title'] =translate($vv['title'], $lan_source, $lan_target);
                }
                $vv['title'] =translate($vv['title'], $lan_source, $lan_target);
                foreach ($vv['attributes'] as &$vvv) {
                    if (!empty($vvv['name'])) {
                        $vvv['name'] =translate($vvv['name'], $lan_source, $lan_target);
                    }
                    if (!empty($vvv['value'])) {
                        $vvv['value'] =translate($vvv['value'], $lan_source, $lan_target);
                    }
                }
                if (!empty($vv['banner']['title'])) {
                    $vv['banner']['title'] =translate($vv['banner']['title'], $lan_source, $lan_target);
                }
            }
            foreach ($en_content['technical']['process'] as $k=>&$v){
                if(!empty($v['des'])){
                    $v['des'] =translate($v['des'],$lan_source,$lan_target);
                }
                if(!empty($v['title'])){
                    $v['title'] =translate($v['title'],$lan_source,$lan_target);
                }
            }
            foreach ($en_content['technical']['information'] as $k=>&$v){
                if(!empty($v['title'])){
                    $v['title'] =translate($v['title'],$lan_source,$lan_target);
                }
                foreach ($v['content'] as $kk=>&$vv){
                    if(!empty($vv['title'])){
                        $vv['title'] =translate($vv['title'],$lan_source,$lan_target);
                    }
                    if(!empty($vv['des'])){
                        $vv['des'] =translate($vv['des'],$lan_source,$lan_target);
                    }
                    if(!empty($vv['tips'])){
                        $vv['tips'] = translate($vv['tips'],$lan_source,$lan_target);
                    }
                }
            }
//            $product['content'] = json_encode($product['content'], JSON_UNESCAPED_UNICODE);
//            $product['content_en'] = json_encode($en_content, JSON_UNESCAPED_UNICODE);
            $product[$field] = json_encode($en_content, JSON_UNESCAPED_UNICODE);
            $model->update($product);
//            print_r($product);
//            die;
        }
    }

//    public function translate($text,$souce='zh',$target='en')
//    {
//        usleep(200000);
//        // 配置腾讯云API密钥
//        $secretId = 'AKIDQyCYtM6xptz9QwWGtaNPUZVHvPrNamu6';
//        $secretKey = '7AOjGoT4e7PWTFqHXggXO6rV2Tkqmtpa';
//
//        // 实例化对象
//        $cred = new Credential(
//            $secretId,
//            $secretKey
//        );
//        $client = new TmtClient($cred, 'ap-beijing');
//// 实例化一个请求对象,每个接口都会对应一个request对象
//        $req = new TextTranslateRequest();
//        $params = array(
//            "SourceText" => $text,
//            "Source" => $souce,
//            "Target" => $target,
//            "ProjectId" => 0
//        );
//        $req->fromJsonString(json_encode($params));
//
//        // 返回的resp是一个TextTranslateResponse的实例，与请求对象对应
//        $resp = $client->TextTranslate($req);
//
//        // 输出json格式的字符串回包
//        $res =  json_decode($resp->toJsonString(),1);
////        print_r($res);die;
//        return $res['TargetText'];
//    }

    public function doFiles()
    {
        $directory = '/Users/wuye/work/php/zzz/JSON'; // 替换为你的目录路径
        $subdirectories = array_filter(scandir($directory), function ($item) use ($directory) {
            return is_dir("$directory/$item") && $item != '.' && $item != '..';
        });
        $model = new \app\common\model\Product();
//        print_r($subdirectories);die;
        Db::execute("truncate table fa_zz_product");

        foreach ($subdirectories as $subdirectory) {
            $filedir = $directory . '/' . $subdirectory;
            $language = $subdirectory;
            // 读取目录内容
            $files = scandir($filedir);
            // 过滤掉当前目录和上级目录的引用
            $files = array_diff($files, array('.', '..'));
            // 输出文件和子目录列表
            foreach ($files as $file) {
                echo $filedir . '/' . $file . "\r\n<br>";

                $model->insert([
                    'type' => $language === '异形管' ? 1 : 0,
                    'status' => 'normal',
                    'language' => $language,
                    'content' => file_get_contents($filedir . '/' . $file),
                    'createtime' => time()
                ]);
//die;
//            print_r( json_decode(file_get_contents($directory.'/'.$file)));die;
            }
        }
        echo 'done';
    }
}